<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>Layui</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<link rel="stylesheet" href="/techshine_war/layui/css/layui.css" media="all">
		<link rel="stylesheet" href="/techshine_war/bootstrap/bootstrap.css" media="all">
		<script src="/techshine_war/layui/layui.all.js" charset="utf-8"></script>
		<script src="/techshine_war/js/jquery.js"></script>
		<script src="/techshine_war/js/global.js" charset="utf-8"></script>
		<!--<script src="../release/wangEditor.js" charset="utf-8"></script>
		<script src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"></script>-->
  <link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">
  <script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
		<style>
			.layui-form-label {
				width: 120px;
			}
			
			.layui-input {
				width: 95%;
			}
			.editor-toolbar {
			  border: 1px solid #ccc;
			}
			
			.editor-text-area {
			  border: 1px solid #ccc;
			  border-top: 0;
			  height: 400px;
			}
		</style>
		<!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
	</head>

	<body>
		<form class="layui-form" id="edit-form" action="" style="margin: 20px;">

			<div class="layui-form-item">
				<label class="layui-form-label">类别</label>
				<div class="layui-input-block">
					<select name="newtype" id="newtype" lay-verify="required" required>
						<option value="1">首页新闻</option>
						<option value="2">首页公告</option>
						<option value="3">毕昇杯新闻</option>
					</select>
				</div>
			</div>
			
			<div class="layui-form-item">
				<label class="layui-form-label">标题</label>
				<div class="layui-input-block">
					<input type="text" name="name" id="name" lay-verify="name" lay-reqtext="标题不能为空" placeholder="请输入1-50字" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">摘要</label>
				<div class="layui-input-block">
					<input type="text" name="code" id="code" lay-verify="code" lay-reqtext="摘要不能为空" placeholder="请输入1-100字" class="layui-input">
				</div>
			</div>
			
			<div class="layui-form-item">
				<label class="layui-form-label">缩略图</label>
				<div class="layui-upload">
				  <button type="button" class="layui-btn" id="test1">上传图片</button><span>建议图片尺寸100*100</span>
				 	<img class="layui-upload-img" id="demo1" style="width: 100px;height: 100px;">
				    <p id="demoText"></p>
				</div>   
			</div>
			<input type="hidden" id="imgurl" name="imgurl" value="" />
			<div id="htmlvaldiv">
				<label class="layui-form-label">文章内容</label>
				<div>
				    <div id="editor-toolbar" class="editor-toolbar"></div>
				    <div id="editor-text-area" class="editor-text-area"></div>
				  </div>
				 <textarea id="htmlval" name="htmlval" style="display: none;"></textarea>
			</div>
			<div style="text-align: center;">
				<input type="hidden" id="id" name="id" value="" />
				<button type="submit" class="layui-btn" lay-submit="" lay-filter="formDemo">立即提交</button>
				<button type="button" class="layui-btn layui-btn-primary" onclick="closePage()">关闭</button>
			</div>

		</form>
		
		<script>
			//Demo
			var id = getQueryString("id");

			var form;
			var submiting = false;
			layui.use(['layer', 'form','upload'], function() {
				//var layedit = layui.layedit;
				var upload = layui.upload;
				var form = layui.form;
				initedit();
				initupload(upload);
				initData(form);
				//自定义验证规则
				form.verify({
					name: function(value) {
						if(value.length < 1 || value.length > 50) {
							return '标题长度1-50';
						}

					},
					code: function(value) {
						if(value.length < 1 || value.length > 100) {
							return '摘要长度1-100';
						}

					}

				});
				//监听提交
				form.on('submit(formDemo)', function(data) {
					if(submiting) {
						return false;
					}
					
					$("#htmlval").val(editor.getHtml());
					var data = $("form").serializeArray();
					console.info(JSON.stringify(data.field))
					$.ajax({
						type: "post",
						url: '/techshine_war/news/insert',
						async: false,
						data: data,
						success: function(res) {
							submiting = true;
							parent.reload();
							closePage();
						}
					});
					return false;
				});
				form.on('select(menutype)', function(data) {
					var sval = data.value;
					if(sval == '1') {
						$("#htmlvaldiv").show()
					} else {
						$("#htmlvaldiv").hide()
					}
					form.render(); //更新全部
					form.render('select');
				});
			});

			function initData(form) {
				if(id != null && id.length > 0) {
					$.ajax({
						type: "get",
						url: '/techshine_war/news/queryByKey?id=' + id,
						async: false,
						success: function(res) {
							echoEdit(res.result);
							$("#name").val(res.result.name);
							$("#code").val(res.result.code);
							$("#newtype").val(res.result.newtype);
							
							$("#imgurl").val(res.result.imgurl);
							$('#demo1').attr('src', res.result.imgurl);
							
							$("#htmlval").val(res.result.htmlval);
							if(res.result.htmlval!=null){
								editor.setHtml(res.result.htmlval)
							}
							form.render('select');
						}
					});
				}else{
					form.render('select');
				}
			}
			var editor ;
			function initedit(){
				const E = window.wangEditor;
				 // Change language
			    const LANG = location.href.indexOf('lang=en') > 0 ? 'en' : 'zh-CN'
			    E.i18nChangeLanguage(LANG)

			    const editorConfig = { MENU_CONF: {} }
			    editorConfig.MENU_CONF['uploadImage'] = {
			      server: '/techshine_war/menu/uploadpic?imgtype=2',
			      // server: '/api/upload-img-10s', // test timeout
			      // server: '/api/upload-img-failed', // test failed
			      // server: '/api/xxx', // test 404

			      timeout: 5 * 1000, // 5s

			      fieldName: 'custom-fileName',
			      meta: { token: 'xxx', a: 100 },
			      metaWithUrl: true, // join params to url
			      headers: { Accept: 'application/json' },
			      maxFileSize: 10 * 1024 * 1024, // 10M

			      base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

			      onBeforeUpload(file) {
			        //console.log('onBeforeUpload', file)

			        return file // will upload this file
			        // return false // prevent upload
			      },
			      onProgress(progress) {
			        //console.log('onProgress', progress)
			      },
			      onSuccess(file, res) {
			      	//console.info(1)
			      	//return res.data[0]
			        //console.log('onSuccess', file, res)
			      },
			      onFailed(file, res) {
			        //alert(res.message)
			        console.log('onFailed', file, res)
			      },
			      onError(file, err, res) {
			        //alert(err.message)
			        console.error('onError', file, err, res)
			      },
			       customInsert(res, insertFn) {
			       	console.info(res)
			       //  console.log('customInsert', res)
			        // const imgInfo = res.data[0];
			       // const { url, alt, href } = imgInfo
			       //  if (!url) throw new Error(`Image url is empty`)
			
			      //   console.log('Your image url ', url)
			         insertFn(res.data[0])
			       }
					
			    }

			     editor = E.createEditor({
			      selector: '#editor-text-area',
			      html: '请输入文章',
			      config: editorConfig,
			      onChange(editor) {
			      	console.log(editor.getHtml())
			      	// 选中文字 
			      	const selectionText = editor.getSelectionText()
			      	document.getElementById('selected-length').innerHTML = selectionText.length 
			      	// 全部文字 
			      	const text = editor.getText().replace(/\n|\r/mg, '');
			      	console.info(text)
			      }
			    })
			    const toolbar = E.createToolbar({
			      editor,
			      selector: '#editor-toolbar',
			      // config: {}
			    })
			}
			var uploadInst;
			function initupload(upload){
				//普通图片上传
				 uploadInst = upload.render({
				    elem: '#test1'
				    ,url: '/techshine_war/menu/uploadpic?imgtype=2'
				    ,accept:'jpg|png|gif|bmp|jpeg'
				    ,before: function(obj){
				      //预读本地文件示例，不支持ie8
				      obj.preview(function(index, file, result){
				        $('#demo1').attr('src', result); //图片链接（base64）
				      });
				    }
				    ,done: function(res){
				      //如果上传失败
				      if(res.errno > 0){
				        return layer.msg('上传失败');
				      }else{
				      	$("#imgurl").val((res.data)[0])
				      }
				      //上传成功
				    }
				    ,error: function(){
				    	$("#imgurl").val("")
				      //演示失败状态，并实现重传
				      layer.msg("图片上传失败")
				      var demoText = $('#demoText');
				      demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
				      demoText.find('.demo-reload').on('click', function(){
				        uploadInst.upload();
				      });
				    }
				  });
			}
		</script>
	</body>

</html>